let chars = []

// 不同的字符有不同的操作
const charMap = {
    '0': { operation: () => { chars.push('0') } },
    '1': { operation: () => { chars.push('1') } },
    '2': { operation: () => { chars.push('2') } },
    '3': { operation: () => { chars.push('3') } },
    '4': { operation: () => { chars.push('4') } },
    '5': { operation: () => { chars.push('5') } },
    '6': { operation: () => { chars.push('6') } },
    '7': { operation: () => { chars.push('7') } },
    '8': { operation: () => { chars.push('8') } },
    '9': { operation: () => { chars.push('9') } },
    '.': { operation: () => { chars.push('.') } },
    '+': { operation: () => { chars.push('+') } },
    '-': { operation: () => { chars.push('-') } },
    '×': { operation: () => { chars.push('×') }, changeChar: '*' },
    '÷': { operation: () => { chars.push('÷') }, changeChar: '/' },
    '=': {
        operation: () => {
            calcResult()
        }
    },
    'c': {
        operation: () => {
            if (chars.length > 0) {
                chars.pop()
            }
        }
    },
}

// 计算结果
function calcResult() {
    try {
        // 获取计算字符串，注意计算字符除法和乘法需要转换
        const str = chars.map(char => charMap[char].changeChar ? charMap[char].changeChar : char).join('')
        // 调用计算脚本
        let result = eval(str)
        if (result === undefined || Infinity === result || isNaN(result)) {
            throw '算不出来'
        }
        // 最多保留6位小数
        result = Math.floor(Math.round(result * 1000000)) / 1000000
        // 回显计算结果
        chars = (result + '').split('')

    } catch (e) {
        //处理异常情况
        alert('算不出来')
    }
}

// 回显到屏幕
function show() {
    const str = chars.join('')
    document.getElementsByClassName('screen')[0].innerHTML = str
}
// 点击字符
function handleClick(char) {
    if (charMap[char] && charMap[char].operation) {
        charMap[char].operation()
        show()
    }
}